﻿using Comm;
using Kinlo.Drv.Drv;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Kinlo.Drv.Machine
{
    public class ElecBalanceMachine
    {
        #region 字段 
        public ElectronicBalanceSocketDrv ElecBalance;
        System.Timers.Timer timer;
        public string ID { get; set; }
        public bool IsWeightFin { get; set; }
        public float Weight { get; set; }
        public string Unit { get; set; }
        public string Symbol { get; set; }
        public int startIndex { get; set; }
        public float CurrWeight { get; set; }
        public bool IsRunning { get; set; }
        public Task RunTask { get; set; }
        #endregion

        #region 方法
        public ElecBalanceMachine(string ip, int port, string id, double interval = 300, int dataLen = 20)
        {
            ID = id;
            ElecBalance = new ElectronicBalanceSocketDrv(ip, port, dataLen);
            timer = new System.Timers.Timer(interval);
            timer.Elapsed += Timer_Elapsed;
            RunTask = Run();
        }
        Object locker1 = new object();
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                HandleMessage(Read());
            }
            catch (Exception ex)
            {
                Logger.Info(string.Format("电子称:{0} {1} 发生异常 {2} ", ElecBalance.IpAddr, ElecBalance.Port, ex));
            }
        }
        public Task Run()
        {
            return Task.Run(() => {
                try
                {
                    while (true)
                    {
                        HandleMessage(Read());
                        Thread.Sleep(50);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Info(string.Format("电子称:{0} {1} 发生异常 {2} ", ElecBalance.IpAddr, ElecBalance.Port, ex));
                }
            });

        }

        public bool IsLoop = true;

        void HandleMessage(byte[] msg)
        {
            try
            {
                if (msg != null && msg.Length >= 16)
                {
                    var sect = Encoding.Default.GetString(msg);
                    var section1 = Encoding.Default.GetString(msg, 0, 2);//ST
                    var section2 = Encoding.Default.GetString(msg, 3, 2);//GS
                    var section3 = Encoding.Default.GetString(msg, 6, 1);//+
                    var section4 = Encoding.Default.GetString(msg, 7, 7);//value
                    var section5 = Encoding.Default.GetString(msg, 15, 2); //\r\n 

                    float w = default(float);
                    float.TryParse(section4, out w);
                    this.CurrWeight = w;
                    Unit = section3;
                    if (section1.ToUpper() == "ST" && (w > 10) && !section3.Contains("-"))
                    {
                        this.Weight = w;
                        this.IsWeightFin = true;
                        Unit = section3;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("HandleMessage {0}", ex),false);
            }
        }
        public bool Connected
        {
            get { return ElecBalance.Connected; }
        }
        public byte[] Read()
        {
            return ElecBalance.Read();
        }
        public void ServiceControl(bool act)
        {
            if (act == false)
            {
                ElecBalance.Disconnect();
            }
            if (act == true && ElecBalance.Connected != true)
            {
                ElecBalance.Open();
                if (RunTask.IsCanceled || RunTask.IsCompleted || RunTask.IsFaulted)
                {
                    RunTask = Run();
                }
            }
            //timer.Enabled = act;
        }
        public void ClearZero()
        {
            ElecBalance.ClearZero();
        }
        #endregion
    }

    public class EBMWeight
    {
        public Decimal Weight { get; set; }
        public string Unit { get; set; }
        public string Symbol { get; set; }
    }
}
